/**
 *
 */
package com.iknight.mgr.controller;

import com.github.pagehelper.PageInfo;
import com.iknight.mgr.api.RoleService;
import com.iknight.mgr.core.base.BaseController;
import com.iknight.mgr.core.constant.IkgConstantCode;
import com.iknight.mgr.core.jstree.JsTreeNode;
import com.iknight.mgr.core.jstree.NodeStatus;
import com.iknight.mgr.core.utils.IkgStringUtils;
import com.iknight.mgr.core.utils.IkgWebUtils;
import com.iknight.mgr.model.RoleModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author Jeryzym
 */
@RestController
@RequestMapping("/rest/role")
@Api(basePath = "/rest/role", value = "角色控制器")
public class RoleController implements BaseController<RoleModel> {
    private static Logger logger = LogManager.getLogger(RoleController.class);
    @Autowired
    private RoleService<RoleModel, String> roleService;

    public RoleModel format(Map<String, Object> params) {
        // TODO Auto-generated method stub
        RoleModel record = new RoleModel();
        record.setRole_id(IkgStringUtils.ObjectToString(params.get("role_id")));

        if (!IkgStringUtils.isNull(params.get("role_code"))) {
            record.setRole_code(IkgStringUtils.ObjectToString(params.get("role_code")));
        }
        if (!IkgStringUtils.isNull(params.get("role_name"))) {
            record.setRole_name(IkgStringUtils.ObjectToString(params.get("role_name")));
        } else {
            /**
             * 判断数据状态，新增 0 修改 1
             */
            if (!IkgStringUtils.isNull(params.get("edit_status"))
                    && IkgStringUtils.ObjectToString(params.get("edit_status")).equals("0")) {
                record.setRole_name("Role_" + IkgStringUtils.randomString(3, 6));
                record.setEffective_date(IkgStringUtils.getCurrentDate("yyyy-MM-dd HH:mm"));
            }
        }
        if (!IkgStringUtils.isNull(params.get("role_group_id"))) {
            record.setRole_group_id(IkgStringUtils.ObjectToString(params.get("role_group_id")));
        }
        if (!IkgStringUtils.isNull(params.get("record_status"))) {
            record.setRecord_status(IkgStringUtils.ObjectToInt(params.get("record_status")));
        }
        if (!IkgStringUtils.isNull(params.get("expire_date"))) {
            record.setExpire_date(IkgStringUtils.ObjectToString(params.get("expire_date")));
        }
        logger.debug(record);
        return record;
    }

    @PostMapping("/save")
    @ApiOperation(httpMethod = "post", value = "save")
//	@RequiresPermissions("mgr.role.save")
//	@RequiresRoles("admin")
    public Object save(@RequestBody Map<String, Object> params, HttpServletRequest request,
                       HttpServletResponse response) {
        // TODO Auto-generated method stub
        if (!isPKeyNotNull(params)) {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
        roleService.save(format(params));
        return IkgWebUtils.postIkgResponse(true, "保存成功!", IkgConstantCode.OPERSUCCESS);
    }

    @PostMapping("/delete")
//	@RequiresPermissions("mgr.role.delete")
//	@RequiresRoles("admin")
    public Object delete(@RequestBody Map<String, Object> params, HttpServletRequest request,
                         HttpServletResponse response) {
        // TODO Auto-generated method stub
        if (!isPKeyNotNull(params)) {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
        roleService.delete(params.get("role_id").toString());
        return IkgWebUtils.postIkgResponse(true, "删除成功!", IkgConstantCode.OPERSUCCESS);
    }

    @PostMapping("/selectOne")
//	@RequiresPermissions("mgr.role.selectone")
//	@RequiresRoles("admin")
    public Object selectOne(@RequestBody Map<String, Object> params, HttpServletRequest request,
                            HttpServletResponse response) {
        // TODO Auto-generated method stub
        if (!isPKeyNotNull(params)) {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
        RoleModel record = roleService.selectOne(params.get("role_id").toString());
        return IkgWebUtils.postIkgResponse(true, "查询成功!", record);
    }

    public Object selectByCond(@RequestBody Map<String, Object> params, HttpServletRequest request,
                               HttpServletResponse response) {
        // TODO Auto-generated method stub
        return null;

    }

    @PostMapping("/repeatCheck")
    public Object repeatChcek(@RequestBody Map<String, Object> params, HttpServletRequest request,
                              HttpServletResponse response) {
        if (params == null || params.get("role_code") == null) {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
        String role_code = params.get("role_code").toString();
        RoleModel record = roleService.getRecordByCode(role_code);
        if (record == null) {
//            return IkgWebUtils.postMsg("通过编码重复检测", true, true);
            return IkgWebUtils.postIkgResponse(true, "通过编码重复检测", IkgConstantCode.OPERSUCCESS);
        }
//        return IkgWebUtils.postMsg("未通过编码重复检测", false, true);
        return IkgWebUtils.postIkgResponse(false, "未通过编码重复检测", IkgConstantCode.OPERSUCCESS);
    }


    @SuppressWarnings("rawtypes")
    @PostMapping("/getUsersByRoleId")
    public Object getUsersByRoleId(@RequestBody Map<String, Object> params, HttpServletRequest request,
                                   HttpServletResponse response) {
        if (!isPKeyNotNull(params)) {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
        //返回树型结构数据
        List<JsTreeNode> treeNodes = new ArrayList<>();
        List<Map> result = roleService.getUsersByRoleId(IkgStringUtils.ObjectToString(params.get("role_id")));
        Iterator ita = result.iterator();
        while (ita.hasNext()) {
            Map map = (Map) ita.next();
            JsTreeNode node = new JsTreeNode();
            node.setId(IkgStringUtils.ObjectToString(map.get("obj_id")));
            node.setText(IkgStringUtils.ObjectToString(map.get("obj_name")));
            if (IkgStringUtils.ObjectToString(map.get("p_obj_id")).length() == 0) {
                node.setParent("#");
            } else {
                node.setParent(IkgStringUtils.ObjectToString(map.get("p_obj_id")));
            }

            if (IkgStringUtils.ObjectToString(map.get("checked")).toLowerCase().equals("false")) {
                node.setState(new NodeStatus(false, false, false, false));
            } else {
                node.setState(new NodeStatus(false, false, true, true));
            }

            if (IkgStringUtils.ObjectToString(map.get("type")).equals("ORG")) {
                node.setIcon("fa fa-bank");
            } else if (IkgStringUtils.ObjectToString(map.get("type")).equals("USER")) {
                node.setIcon("fa fa-user");
            }
            JSONObject attr = new JSONObject();
            attr.put("type", IkgStringUtils.ObjectToString(map.get("type")));
            node.setAttributes(attr);
            treeNodes.add(node);
        }
        return JSONArray.fromObject(treeNodes);
    }

    @SuppressWarnings("rawtypes")
    @PostMapping("/getPermsByRoleId")
    public Object getPermsByRoleId(@RequestBody Map<String, Object> params, HttpServletRequest request,
                                   HttpServletResponse response) {
        if (!isPKeyNotNull(params)) {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
        List<JsTreeNode> treeNodes = new ArrayList<>();
        List<Map> result = roleService.getPermsByRoleId(IkgStringUtils.ObjectToString(params.get("role_id")));
        Iterator ita = result.iterator();
        while (ita.hasNext()) {
            Map map = (Map) ita.next();
            JsTreeNode node = new JsTreeNode();
            node.setId(IkgStringUtils.ObjectToString(map.get("obj_id")));
            node.setText(IkgStringUtils.ObjectToString(map.get("obj_name")));
            if (IkgStringUtils.ObjectToString(map.get("p_obj_id")).length() == 0) {
                node.setParent("#");
            } else {
                node.setParent(IkgStringUtils.ObjectToString(map.get("p_obj_id")));
            }
            if (IkgStringUtils.ObjectToString(map.get("checked")).toLowerCase().equals("false")) {
                node.setState(new NodeStatus(false, false, false, false));
            } else {
                node.setState(new NodeStatus(false, false, true, true));
            }
            if (IkgStringUtils.ObjectToString(map.get("type")).equals("GROUP")) {
                node.setIcon("fa fa-balance-scale");
            } else if (IkgStringUtils.ObjectToString(map.get("type")).equals("PERM")) {
                node.setIcon("fa fa-user");
            }
            JSONObject attr = new JSONObject();
            attr.put("type", IkgStringUtils.ObjectToString(map.get("type")));
            node.setAttributes(attr);
            treeNodes.add(node);
        }

        return JSONArray.fromObject(treeNodes);
    }

    @SuppressWarnings("rawtypes")
    @PostMapping("/getMenusByRoleId")
    public Object getMenusByRoleId(@RequestBody Map<String, Object> params, HttpServletRequest request,
                                   HttpServletResponse response) {
        if (!isPKeyNotNull(params)) {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
        List<Map> menus = roleService.getMenusByRoleId(params.get("role_id").toString());
        if (null == menus || menus.size() == 0) {
            return IkgWebUtils.postIkgResponse(true, "未查询到符合条件的数据", IkgConstantCode.OPERSUCCESS);
        }
        List<JsTreeNode> treeNodes = new ArrayList<>();
        Iterator<Map> ita = menus.iterator();
        JSONObject jo = new JSONObject();
        while (ita.hasNext()) {
            Map map = ita.next();
            JsTreeNode jsTreeNode = new JsTreeNode();
            jsTreeNode.setId(IkgStringUtils.ObjectToString(map.get("menu_id")));
            jsTreeNode.setText(IkgStringUtils.ObjectToString(map.get("menu_name")));
            jsTreeNode.setIcon(IkgStringUtils.ObjectToString(map.get("icon_cls")));

            if (IkgStringUtils.ObjectToString(map.get("p_menu_id")).length() == 0) {
                jsTreeNode.setParent("#");
            } else {
                jsTreeNode.setParent(IkgStringUtils.ObjectToString(map.get("p_menu_id")));
            }
            if (!IkgStringUtils.ObjectToString(map.get("checked")).toLowerCase().equals("false")) {
                jsTreeNode.setState(new NodeStatus(false, false, true, true));
            } else {
                jsTreeNode.setState(new NodeStatus(false, false, false, false));
            }
            JSONObject attr = new JSONObject();
            attr.put("isLeaf", map.get("isleaf"));
            jsTreeNode.setAttributes(attr);
            treeNodes.add(jsTreeNode);
        }
        return JSONArray.fromObject(treeNodes);
    }

    @PostMapping("/grantRoleToUser")
    public Object grantRoleToUser(@RequestBody Map<String, Object> params, HttpServletRequest request,
                                  HttpServletResponse response) {
        if (!isPKeyNotNull(params)) {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
        roleService.grantRoleToUser(params);
        return IkgWebUtils.postIkgResponse(true, "授权成功!", IkgConstantCode.OPERSUCCESS);
    }

    @PostMapping("/grantPermToRole")
    public Object grantPermToRole(@RequestBody Map<String, Object> params, HttpServletRequest request,
                                  HttpServletResponse response) {
        if (!isPKeyNotNull(params)) {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
        roleService.grantPermToRole(params);
        return IkgWebUtils.postIkgResponse(true, "授权成功!", IkgConstantCode.OPERSUCCESS);
    }

    /**
     * @param params
     * @param request
     * @param response
     * @return
     * @description 菜单授权
     */
    @PostMapping("/grantMenuToRole")
    public Object grantMenuToRole(@RequestBody Map<String, Object> params, HttpServletRequest request,
                                  HttpServletResponse response) {
        if (!isPKeyNotNull(params)) {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
        roleService.grantMenuToRole(params);
        return IkgWebUtils.postIkgResponse(true, "授权成功!", IkgConstantCode.OPERSUCCESS);
    }

    public boolean isPKeyNotNull(Map<String, Object> params) {
        return params != null && params.get("role_id") != null;
    }

    @Override
    @PostMapping("/list")
//	@RequiresPermissions("mgr.role.list")
//	@RequiresRoles("admin")
    public Object selectByPage(@RequestBody Map<String, Object> params, HttpServletRequest request,
                               HttpServletResponse response) {
        // TODO Auto-generated method stub
        int pageIndex = 0;
        int pageSize = 0;
        if (params == null) {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
        pageIndex = IkgStringUtils.ObjectToInt(params.get("pageNumber"));
        pageSize = IkgStringUtils.ObjectToInt(params.get("pageSize"));
        PageInfo<RoleModel> roles = roleService.selectPage(params, pageIndex, pageSize);
        return IkgWebUtils.postResult(roles.getTotal(), roles.getList());
    }
}
